
package com.example.testutil.util.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;

import com.example.testutil.util.LogUtil;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class DownloadUtil {
    private static DownloadUtil mDownloadUtil;

    private HttpURLConnection mHttpURLConnection;

    private InputStream mInputStream;

    private FileOutputStream mOutputStream;

    private long total;

    private URL mUrl;

    private int progress;

    private DownloadUtil() {
    };

    public static DownloadUtil getInstance() {
        if (mDownloadUtil == null) {
            mDownloadUtil = new DownloadUtil();
        }
        return mDownloadUtil;
    }

    public void doDownload(String url, String path, String filename) {

        try {
            if (mUrl == null) {
                mUrl = new URL(url);
            }
            mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mHttpURLConnection.setConnectTimeout(3 * 1000);
            mHttpURLConnection.connect();

            File savepath = new File(path);
            if (!savepath.exists()) {
                savepath.mkdir();
            }
            File mFile = new File(savepath, filename);
            if (mFile.exists()) {
                mFile.delete();
            }

            mInputStream = mHttpURLConnection.getInputStream();
            File write = new File(savepath, filename);
            mOutputStream = new FileOutputStream(write);

            total = mHttpURLConnection.getContentLength();

            byte[] data = new byte[4 * 1024];

            int count = 0;

            int size = 0;
            while ((count = mInputStream.read(data)) != -1) {
                mOutputStream.write(data, 0, count);
                size += count;
                progress =  (int) (size* 100 / total) ;
                
                LogUtil.d("size------" + size+"progress-----"+ progress+"total-------"+total);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (mInputStream != null) {
                    mInputStream.close();
                }
                if (mOutputStream != null) {
                    mOutputStream.close();
                }
                if (mHttpURLConnection != null) {
                    mHttpURLConnection.disconnect();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    /*
     * 通过httpconnection来下载文件.
     */
    public void execute(String url,String path,String filename,Object object) {
        new DownloadTask(url, path, filename, object).execute();
    }
     class DownloadTask extends AsyncTask<String, Integer, Boolean> {
        private String url;

        private String path;

        private String filename;

        private Object object;

        private HttpURLConnection mHttpURLConnection;

        private InputStream mInputStream;

        private FileOutputStream mOutputStream;

        private long total;

        private URL mUrl;

        private int progress;

        public DownloadTask(String url, String path, String filename, Object object) {
            this.url = url;
            this.path = path;
            this.filename = filename;
            this.object = object;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {

            } else {

            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            int progress = values[0];
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                if (mUrl == null) {
                    mUrl = new URL(url);
                }
                mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
                mHttpURLConnection.setConnectTimeout(3 * 1000);
                mHttpURLConnection.connect();

                File savepath = new File(path);
                if (!savepath.exists()) {
                    savepath.mkdir();
                }
                File mFile = new File(savepath, filename);
                if (mFile.exists()) {
                    mFile.delete();
                }

                mInputStream = mHttpURLConnection.getInputStream();
                File write = new File(savepath, filename);
                mOutputStream = new FileOutputStream(write);

                total = mHttpURLConnection.getContentLength();

                byte[] data = new byte[4 * 1024];

                int count = 0;

                int size = 0;
                while ((count = mInputStream.read(data)) != -1) {
                    mOutputStream.write(data, 0, count);
                    size += count;
                    progress = (int) (size * 100/ total) ;
                    
                    publishProgress(progress);
                    
                    LogUtil.d("size------" + size+"progress-----"+progress);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (mInputStream != null) {
                        mInputStream.close();
                    }
                    if (mOutputStream != null) {
                        mOutputStream.close();
                    }
                    if (mHttpURLConnection != null) {
                        mHttpURLConnection.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }

    }
     /*
      * 暂时不生效
      */
     public static boolean isDownloadManagerAvailable(Context context) {
         try {
             if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
                 return false;
             }
             Intent intent = new Intent(Intent.ACTION_MAIN);
             intent.addCategory(Intent.CATEGORY_LAUNCHER);
             intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
             List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
                     PackageManager.MATCH_DEFAULT_ONLY);
             return list.size() > 0;
         } catch (Exception e) {
             return false;
         }
     }
     
     public static void downloadFile(Context context,String url,String path,String filename) {
         DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
         request.setDescription("Some descrition");
         request.setTitle("Some title");
         // in order for this if to run, you must use the android 3.2 to compile your app
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
             request.allowScanningByMediaScanner();
             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
         }
         request.setDestinationInExternalPublicDir(path, filename);
         // get download service and enqueue file
         DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
         manager.enqueue(request);
     }
     public static void GetWithOkttp(String url) {
         OkHttpClient mClient = new OkHttpClient();
         final Request mRequest = new Request.Builder().url(url).build();
         Call mCall = mClient.newCall(mRequest);
         mCall.enqueue(new Callback() {
            
            @Override
            public void onResponse(Response arg0) throws IOException {
                LogUtil.d("arg0--------------"+arg0.body().string());
            }
            
            @Override
            public void onFailure(Request arg0, IOException arg1) {
                
            }
        });
     }
}
